<?php 
//define('TWITTER_CONSUMERKEY',        '*********************');
//define('TWITTER_CONSUMERSECRET',     '******************************************');
//define('TWITTER_ACCESSTOKEN_KEY',    '**************************************************');
//define('TWITTER_ACCESSTOKEN_SECRET', '******************************************');
/*
 * Twitter class, by Olivier St-Laurent
 * 
 * Must define TWITTER_CONSUMERKEY, TWITTER_CONSUMERSECRET, TWITTER_ACCESSTOKEN_KEY, TWITTER_ACCESSTOKEN_SECRET in config.php
 * 
 * Usage : 
        
        $twitter = new twitter();
        $twitter->getTimeline("TwitterUser", 12, 4); // Fetch twitter feeds from user TwitterUser, within the 10 more recent, show the last 4 feeds that TwitterUser posted. Leave empty or false in the last parameter to fetch all 12 more recent feeds. 
        $twitter->showDates = true;
        $twitter->showName = true;
        $twitter->showPictures = true;
        $twitterFeed = $twitter->parseTimelineToHtml();
        $twitterUserInfo = $twitter->getUserInfo($this->designer['twitter']);
        $twitterName = $twitterUserInfo->name;
   
 * 
 * Example of HTML output per feed : 
 * 
    <img src='***' />
    <p>
        <span>DATE</span><br />
        Feed Text
    </p>
    
 */
class Twitter {
    
    public $consumerKey   = TWITTER_CONSUMERKEY;
    public $consumerSecret = TWITTER_CONSUMERSECRET;
    public $accessTokenKey  = TWITTER_ACCESSTOKEN_KEY;
    public $accessTokenSecret = TWITTER_ACCESSTOKEN_SECRET;
    
    public $baseUrl = "https://api.twitter.com/";
    public $apiVersion = "1.1";
    
    public $screen_name = null;
    public $response = null;
    public $json_response = null;
    
    public $ownsOnly = false;
    public $showPictures = false;
    public $showDates = false;
    
    public $css_linkClass = 'link';
    public $css_tagsClass = 'hash';
    public $css_userClass = 'user';
    
    public $dateFormat = "d M";
    
    public function get($url, $params=array()) {
        if(!preg_match("#^https?://#i",$url)){
            $url= $this->baseUrl.$this->apiVersion."/".$url;
        }
        $oauthOptions = array(
            'requestScheme'   => Zend_Oauth::REQUEST_SCHEME_HEADER,
            'version'         => '1.0',
            'signatureMethod' => 'HMAC-SHA1',
            'consumerKey'     => $this->consumerKey,
            'consumerSecret'  => $this->consumerSecret,
        );
        $token = new Zend_Oauth_Token_Access();
        $token->setParams(array(
            'oauth_token'        => $this->accessTokenKey,
            'oauth_token_secret' => $this->accessTokenSecret,
        ));
        $client = $token->getHttpClient($oauthOptions);
        $client->setUri($url);
        $client->setMethod(Zend_Http_Client::GET);
        foreach($params as $param => $value)
            $client->setParameterGet($param, $value);
        $this->response = $client->request();
        return $this->json_response = json_decode($this->response->getBody());
    }
    
    public function getTimeline($user,$count=10,$ownsOnly=false) {
        $this->screen_name = $this->getNameFromUrl($user);
        $this->ownsOnly = $ownsOnly;
        return $this->get('statuses/user_timeline.json', array('screen_name' => $this->screen_name, 'count' => $count));
    }
    
    public function getUserInfo($user) {
        $this->screen_name = $this->getNameFromUrl($user);
        return current($this->get('users/lookup.json', array('screen_name' => $this->screen_name)));
    }
    
    public function formatDate($date) {
        return date($this->dateFormat, strtotime($date));
    }
    
    public function parseTimelineToHtml($jsonDecoded=null) {
        if ($jsonDecoded === null) $jsonDecoded = $this->json_response;
        if ($jsonDecoded === null) return null;
        $twitterFeed = "";
        $i = 0;
        foreach ($jsonDecoded as $tweet) {
            if (!$this->ownsOnly || strtolower($tweet->user->screen_name) == strtolower($this->screen_name)) {
                if(!isset($tweet->text))return;
                $text = $tweet->text;
                foreach ($tweet->entities->urls as $url) {
                    $text = str_replace($url->url, '<a class="'.$this->css_linkClass.'" href="'.$url->url.'">'.$url->display_url.'</a>', $text);
                }
                foreach ($tweet->entities->hashtags as $hash) {
                    $text = str_replace('#'.$hash->text, '<a class="'.$this->css_tagsClass.'" href="http://twitter.com/search?q=%23'.$hash->text.'&src=hash">#'.$hash->text.'</a>', $text);
                }
                foreach ($tweet->entities->user_mentions as $user) {
                    $text = str_replace('@'.$user->screen_name, '<a class="'.$this->css_userClass.'" href="http://twitter.com/@'.$user->screen_name.'">@'.$user->screen_name.'</a>', $text);
                }
                if ($this->showPictures) $twitterFeed .= "<img src='".$tweet->user->profile_image_url_https."' />";
                $twitterFeed .= "<p>";
                if ($this->showDates) $twitterFeed .= "<span>".$this->formatDate($tweet->created_at)."</span><br />";
                $twitterFeed .= $text;
                $twitterFeed .= "</p>";
                if ($this->ownsOnly && ++$i == $this->ownsOnly) break;
            }
        }
        return $twitterFeed;
    }
    
    public function __toString() {
        ob_start();
        echo '<pre>';
        print_r($this->json_response);
        echo '</pre>';
        return ob_get_clean();
    }
    
    public function getNameFromUrl($url) {
        return preg_replace("#(^.*/@?)|(^)([a-z0-9_\.-]+)$#iu", "$3", $url);
    }
    
}
